package com.song.boot.springstudy.thread.concurrent;

import java.util.concurrent.Semaphore;


/**
 * 信号量
 * 有几个信号量就可以同时执行几个线程
 * 应用场景：服务限流 让你几个请求进来、就只能几个
 */
public class T11_TestSemaphore {
    public static void main(String[] args) {
        //Semaphore s = new Semaphore(2);
        // fair 公平非公平
        // 有几个信号量
        Semaphore s = new Semaphore(3, false);
        //允许一个线程同时执行
        //Semaphore s = new Semaphore(1);

        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T1 running...");
                Thread.sleep(200);
                System.out.println("T1 running...");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }).start();

        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T2 running...");
                Thread.sleep(200);
                System.out.println("T2 running...");

                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();


        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T3 running...");
                Thread.sleep(200);
                System.out.println("T3 running...");

                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();



        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T4 running...");
                Thread.sleep(200);
                System.out.println("T4 running...");

                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}